<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>06_列表渲染_过滤与排序</title>
  </head>
  <body>
    <!--
1. 列表过滤
2. 列表排序
-->
    <div id="root">
      <input type="text" placeholder="请输入搜索内容" v-model="searchText" />
      <ul>
        <li v-for="person in filterPersons" :key="person.id">
          {{person.id}} -- {{person.name}} -- {{person.age}}
        </li>
      </ul>
      <!-- 函数体代码只有一条语句，可以直接写 -->
      <button @click="orderType = 1">年龄升序</button>
      <button @click="orderType = -1">年龄降序</button>
      <button @click="orderType = 0">原本顺序</button>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      new Vue({
        el: "#root",
        data: {
          orderType: 0, // 0：原本顺序 -1：降序  1：升序
          searchText: "",
          persons: [
            { id: 1, name: "jack", age: 20 },
            { id: 2, name: "rose", age: 18 },
            { id: 3, name: "tom", age: 38 },
            { id: 4, name: "jerry", age: 40 },
            { id: 5, name: "lilei", age: 22 },
            { id: 6, name: "lipeihua", age: 3 },
          ],
          // filterPersons: [],
        },
        computed: {
          // 搜索后的persons
          filterPersons() {
            // 1. 准备参与计算的数据
            const { searchText, persons, orderType } = this;
            // 2. 开始计算
            const filterPersons = persons.filter((person) => {
              return person.name.indexOf(searchText) !== -1;
            });

            // 原本顺序，不进行排序
            if (orderType === 0) {
              return filterPersons;
            }

            const sortedPersons = filterPersons.sort((a, b) => {
              // return a.age - b.age; // 升序
              // return b.age - a.age; // 降序
              return orderType === 1 ? a.age - b.age : b.age - a.age;
            });
            // 3. 将计算后的结果返回
            return sortedPersons;
          },
        },
      });
    </script>
  </body>
</html>
